package simplehttpserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;

public class HttpServer {
	public static final String WEB_ROOT = System.getProperty("user.dir")+File.separator+"ROOT";
	public static final String SHUTDOWN = "/shutdown";
	public static final String CONF = System.getProperty("user.dir")+File.separator+"conf/server.conf";	
	private static int port = 8080;
	private static String host = "127.0.0.1";
	private boolean shutdown = false;
	
	static {
		try {
			InputStream in = new FileInputStream(CONF);
			Properties info = new Properties();
			info.load(in);
			if(info.getProperty("port") != null) {
				port = Integer.parseInt(info.getProperty("port"));
			}
			if(info.getProperty("host")!= null) {
				host = info.getProperty("host");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void await() {
		
		ServerSocket serverSocket = null;
		// 创建ServeSocket
		try {
			serverSocket = new ServerSocket(port , 1, 
					InetAddress.getByName(host));
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}	
		// 循环监听请求
		while(!shutdown) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				InputStream input = socket.getInputStream();
				OutputStream output = socket.getOutputStream();
				// 解析请求
				Request request = new Request(input);
				request.parse();
				// 创建响应对象
				Response response = new Response(output);
				response.setRequest(request);
				response.sendStaticResourse();
				// 关闭Socket
				socket.close();
				shutdown = request.url.equals(SHUTDOWN);
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				socket = null;
			}
		}		
	}
	// start
	public static void main(String[] a) {
		HttpServer server = new HttpServer();
		server.await();
	}
}
